<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
    <!-- 引入SockJS和STOMP库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.2/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script>
        let stompClient;

        function connect() {
            // 创建SockJS连接
            const socket = new SockJS('/chat');
            stompClient = Stomp.over(socket);
            // 建立连接
            stompClient.connect({}, function (frame) {
                console.log('Connected: ' + frame);
                // 订阅 /topic/public 主题，接收服务器推送的消息
                stompClient.subscribe('/topic/public', function (message) {
                    if (message.body) {
                        // 解析接收到的JSON消息
                        const chatMessage = JSON.parse(message.body);
                        // 将消息打印到控制台
                        console.log(chatMessage.sender + ": " + chatMessage.content);
                        // 在页面上显示消息
                        const messageList = document.getElementById('messageList');
                        const p = document.createElement('p');
                        p.textContent = chatMessage.sender + ": " + chatMessage.content;
                        messageList.appendChild(p);
                    }
                });
            }, function (error) {
                console.log('Error: ' + error);
            });
        }

        function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value;
            if (message) {
                const chatMessage = {
                    sender: 'User',
                    content: message
                };
                // 发送消息到服务器
                stompClient.send('/app/sendMessage', {}, JSON.stringify(chatMessage));
                messageInput.value = '';
            }
        }

        window.onload = connect;
    </script>
</head>
<body>
<input type="text" id="messageInput" placeholder="输入消息">
<button onclick="sendMessage()">发送</button>
<div id="messageList"></div>
</body>
</html>